﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Lightray.Hattrick.ChppLib.EntityTypes
{
    public class EntityCollection<T> : IList<T> where T : EntityBase
    {
        private IList<T> _baseCollection;

        internal EntityCollection(IEnumerable<T> baseCollection)
        {
            _baseCollection = baseCollection.ToList();
        }

        public T ById(int entityId)
        {
            return _baseCollection.FirstOrDefault(entity => entity.ID == entityId);
        }

        #region IList<T> Members

        public int IndexOf(T item)
        {
            return _baseCollection.IndexOf(item);
        }

        void IList<T>.Insert(int index, T item)
        {
            throw new NotSupportedException("Not allowed");
        }

        void IList<T>.RemoveAt(int index)
        {
            throw new NotSupportedException("Not allowed");
        }

        public T this[int index]
        {
            get
            {
                return _baseCollection[index];
            }
            set
            {
                throw new NotSupportedException("Not allowed");
            }
        }

        #endregion

        #region ICollection<T> Members

        void ICollection<T>.Add(T item)
        {
            throw new NotSupportedException("Not allowed");
        }

        void ICollection<T>.Clear()
        {
            throw new NotSupportedException("Not allowed");
        }

        public bool Contains(T item)
        {
            return _baseCollection.Contains(item);
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            _baseCollection.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _baseCollection.Count; }
        }

        public bool IsReadOnly
        {
            get { return true; }
        }

        bool ICollection<T>.Remove(T item)
        {
            throw new NotSupportedException("Not allowed");
        }

        #endregion

        #region IEnumerable<T> Members

        public IEnumerator<T> GetEnumerator()
        {
            return _baseCollection.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotSupportedException("Not allowed");
        }

        #endregion

        public override string ToString()
        {
            return string.Format("List of {0} {1}", _baseCollection.Count, typeof(T).ToString());
        }
    }
}
